package models
import Tables._
import scala.slick.driver.MySQLDriver.simple._

object Tag {

  /**
   * 通过文章id来找到所有的tag
   */
  def findTags(aid: Int): List[String] = {
    SlickDB.database.withSession {
      implicit session =>
        val tagsId = ArticleCategory.filter(_.aId === aid).map(_.cId)
        val query = Category.filter(_.id in tagsId).map(_.name)
        val tags: List[String] = query.list
        tags
    }
  }
  
  def tags={
     SlickDB.database.withSession {
      implicit session =>
         val tagList = Tables.Category.map(_.name).list
         tagList
     }
  }
  
  def deleteArticleTags(aid:Int) = {
    SlickDB.database.withSession {
      implicit session =>
        val q=Tables.ArticleCategory.filter(_.aId === aid)
        q.delete
    }
  }
  
  
  def addTags(aid:Int,tags:List[String]) = {
    SlickDB.database.withSession {
      implicit session =>
       tags.foreach(tag => {
           val option=Tables.Category.filter(_.name === tag).firstOption
           option match {
             case Some(t) =>
               Tables.ArticleCategory+=ArticleCategoryRow(aid,t.id)
             case None =>
               val cid=(Tables.Category returning Tables.Category.map(_.id))+=CategoryRow(0,tag)
               Tables.ArticleCategory+=ArticleCategoryRow(aid,cid)
           }
           
       })
    }
  }

}